<template>
  <BasicTable @register="registerTable" :row-selection="rowSelection">
    <template #tableTitle>
      <a-input placeholder="搜索媒体" allowClear style="width: 30%; margin-bottom: 5px; margin-right: 20px" @press-enter="handleSearch" />
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleOpenGroupModal">新增分组</a-button>
      <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="handleUpload" :accept="fileTypeLimit">上传</j-upload-button>
      <!-- <MySelectMaterial :fileMax="10" biz-type="test"/> -->
      <a-dropdown v-if="checkedKeys.length > 0 && !isSelectModel">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="i-ant-design:delete-outlined" />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button
          >批量操作
          <Icon icon="i-mdi:chevron-down" />
        </a-button>
      </a-dropdown>
    </template>
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" />
    </template>

    <template #media="{ record }">
      <div class="media-material">
        <ImagePreview
          class="material-image-preview"
          v-if="record.type === MaterialType.IMAGE.type"
          :image-list="[{ src: record.url, width: 80, height: 80 }]"
        />

        <MySimpleAudioPlayer
          v-if="record.type === MaterialType.VOICE.type"
          :audioList="[{ url: record.url }]"
          :show-prev-button="false"
          :show-next-button="false"
          :show-playback-rate="false"
          :show-volume-button="false"
          :show-progress-bar="false"
          :isLoop="false"
          @loaded-metadata="({ duration }) => (record.duration = duration)"
        />
        <span class="media-voice-duration" v-if="record.type === MaterialType.VOICE.type">
          {{ record.duration ? record.duration : "0.00" }}
        </span>

        <div class="media-material-name">{{ record.name }}</div>
      </div>
    </template>
  </BasicTable>
  <MaterialDrawer @register="registerMaterialDrawer" @success="handleReload" />
</template>
<script lang="ts" name="MaterialList" setup>
  import { ref, unref, onMounted, onUnmounted, nextTick, watchEffect } from "vue"
  import { downloadByOnlineUrl } from "/@/utils/file/download"
  import { BasicTable, TableAction } from "/@/components/Table"
  import { useDrawer } from "/@/components/Drawer"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { ImagePreview } from "/@/components/Preview/index"
  import { columns, searchFormSchema, MaterialType, getUploadBizType } from "../material.data"
  import { pageMaterial, saveOrUpdateMaterial, deleteMaterial, batchDeleteMaterial } from "/@/api/infra/material"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { propTypes } from "/@/utils/propTypes"
  import { uploadApi } from "/@/api/sys/upload"
  import { getFileConfig } from "/@/api/infra/file"
  // import MySelectMaterial from '../MySelectMaterial.vue'
  import { UploadBizType } from "/@/enums/uploadEnum"
  import MaterialDrawer from "./MaterialDrawer.vue"
  import MySimpleAudioPlayer from "/@/components/My/MySimpleAudioPlayer.vue"
  import { Icon } from "/@/components/Icon"

  const [registerMaterialDrawer, { openDrawer: openMaterial }] = useDrawer()
  const { createMessage } = useMessage()
  const emit = defineEmits(["open-group", "update:value", "select-change"])

  const props = defineProps({
    groupId: propTypes.string.def(undefined),
    isSelectModel: propTypes.bool.def(false),
    selectCount: propTypes.number.def(-1), // -1不限制
    // 素材类型
    materialType: propTypes.string.def(MaterialType.IMAGE.name),
  })

  const fileTypeLimit = ref("*")
  const searchParams = ref<any>({})
  const lastUpdateRecord = ref<any>()

  console.log("props.isSelectModel", props.isSelectModel)
  // 列表页面公共参数、方法
  const { prefixCls, tableContext } = useListPage({
    designScope: "material-list",
    tableProps: {
      api: pageMaterial,
      beforeFetch: (params) => {
        for (const key in searchParams.value) {
          params[key] = searchParams.value[key]
        }
        params.groupId = unref(props.groupId)
        params.type = unref(props.materialType)
      },
      showIndexColumn: false,
      striped: false,
      columns: columns,
      bordered: false,
      actionColumn: {
        width: 140,
        title: "操作",
        dataIndex: "action",
        fixed: "right",
        slots: { customRender: "action" },
      },
      immediate: false,
      // canResize: props.isSelectModel ? false : true,
      canResize: true,
      showTableSetting: false,
      clickToRowSelect: props.isSelectModel ? true : false,
      resizeHeightOffset: props.isSelectModel ? 62 : 0,
      rowSelectionTipType: props.isSelectModel ? "onTableTitle" : "onTableTop",
      useSearchForm: false,
      formConfig: {
        showSubmitButton: false,
        showResetButton: false,
        schemas: searchFormSchema,
      },
    },
  })
  const checkedKeys = ref<Array<string | number>>([])

  /**
   * 选择列配置
   */
  const rowSelection = {
    type: props.selectCount === 1 ? "radio" : "checkbox", // 为 radio 是单选
    columnWidth: 50,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  }

  onUnmounted(() => {
    console.log("onUnmounted-props", unref(props))
  })

  const [registerTable, { reload, clearSelectedRowKeys, getSelectRows }, {}] = tableContext

  watchEffect(() => {
    if (props.groupId) {
      nextTick(() => {
        clearSelectedRowKeys()
        reload()
      })
    }

    if (props.materialType) {
      nextTick(() => {
        initFileLimitType()
      })
    }
  })

  const initFileLimitType = async () => {
    if (props.materialType) {
      const data = await getFileConfig({ bizType: getUploadBizType(props.materialType) })
      fileTypeLimit.value = !data.fileTypeLimit || data.fileTypeLimit === "" ? "*" : data.fileTypeLimit
    }
  }

  const handleOpenGroupModal = () => {
    console.log("materialType", unref(props.materialType))

    emit("open-group", unref(props.materialType))
  }

  /**
   * 选择事件
   */
  function onSelectChange(selectedRowKeys: (string | number)[]) {
    checkedKeys.value = selectedRowKeys
    console.log("selectedRowKeys", selectedRowKeys)
    emit("select-change", getSelectRows())
  }

  const handleUpload = async (data) => {
    if (!data.file) {
      return
    }
    console.log("upload: ", data)
    createMessage.loading({
      content: `正在上传...`,
      key: "upload_material",
      duration: 0,
    })

    try {
      // 上传文件
      const result = await uploadApi(
        {
          name: "file",
          file: data.file,
          data: {
            bizType: getUploadBizType(props.materialType),
          },
        },
        (e) => {
          // console.log(e);
        },
        true
      )
      console.log("upload result: ", result)

      // 开始保存素材记录
      const materialForm = {
        url: result.data,
        type: props.materialType,
        groupId: props.groupId,
        name: data.file.name,
        size: data.file.size / 1000,
      }
      console.log("materialForm", materialForm)
      await saveOrUpdateMaterial(materialForm, false)

      createMessage.success({
        content: `上传成功`,
        key: "upload_material",
        duration: 2,
      })
      reload()
    } catch (e) {
      createMessage.error({
        content: `上传失败`,
        key: "upload_material",
        duration: 2,
      })
    }
  }

  const handleSearch = (e) => {
    const keyWord = e.target.value
    searchParams.value.name = keyWord
    console.log("search keyword: ", keyWord)
    reload()
  }

  function handleEdit(record) {
    lastUpdateRecord.value = record
    openMaterial(true, {
      materialType: props.materialType,
      fileTypeLimit: fileTypeLimit.value,
      record,
      isUpdate: true,
    })
  }

  async function handleDelete(record) {
    await deleteMaterial({ id: record.id }, reload)
  }

  async function batchHandleDelete() {
    await batchDeleteMaterial({ ids: checkedKeys.value }, reload)
  }

  const handleDownload = (record) => {
    downloadByOnlineUrl(record.url, record.name)
  }

  function getTableAction(record) {
    return [
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
      },
      {
        label: "下载",
        onClick: handleDownload.bind(null, record),
      },
      {
        label: "删除",
        color: "error",
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
    ]
  }

  const handleReload = () => {
    nextTick(() => {
      // 因为文件采用替换方式(地址不变), 需要加个随机参数, 触发页面更新图片/视频预览图
      if (lastUpdateRecord.value) {
        lastUpdateRecord.value.url = lastUpdateRecord.value.url + "?t=" + new Date().getTime()
      }
      reload()
    })
  }

  defineExpose({ reload })
</script>

<style lang="less">
  .media-material {
    display: flex;
    align-items: center;
  }
  .media-material-name {
    margin-left: 10px;
  }
  .material-image-preview {
    img {
      width: 80px !important;
      height: 80px !important;
    }
  }

  .media-voice-duration {
    margin-left: -10px;
    margin-right: 5px;
  }
</style>
